# -*- coding: utf-8 -*-
import datetime

from flask import Blueprint, render_template, request, url_for, redirect, jsonify

from application import db
from common.libs.UserSerivice import UserService
from common.libs.render_helper import ops_render
from web.models.AppAccessLog import AppAccessLog

from web.models.user import User

route_account = Blueprint('account_page', __name__)


@route_account.route("/index")
def index():
    # return render_template("account/index.html")
    # 取得所有账号信息
    user_list = User.query.all()
    # 构建一个context字典传给ops_render方法去渲染
    context = {'account_list': user_list}
    return ops_render("account/index.html", context)


# 用于查看某个账号信息
@route_account.route("/info")
def info():
    # return render_template("account/info.html")
    context = {}
    req = request.args
    # 获取查询账号请求的id，如果没输入返回0
    uid = int(req.get("id", 0))
    # 定义一个跳转对象
    reback_url = url_for('account_page.index')
    if uid < 1:
        return redirect(reback_url)  # 如果没输入则重定向至首页
    info = User.query.filter_by(uid=uid).first()  # 查询账号列表uid符合的
    if not info:  # 如果搜索结果为空
        return redirect(reback_url)
    context["info"] = info
    AppAccessLog.query.filter_by()
    return ops_render("account/info.html", context)


@route_account.route("/set", methods=['GET', 'POST'])
def set():
    # return render_template("account/set.html")
    if request.method == "GET":
        context = {}
        # args返回请求的参数，values返回请求中的参数和form
        req = request.args
        uid = int(req.get("id", 0))
        info = None
        # 因为新增账号页面和修改账号页面是同一个，但渲染不一样
        if uid:  # 所以如果获取到请求的id参数，则是通过点击修改进来的页面
            info = User.query.filter_by(uid=uid).first()
        context["info"] = info
        return ops_render("account/set.html", context)

    # 处理POST请求
    if request.method == "POST":
        req = request.values
        nickname = req["nickname"] if "nickname" in req else ""
        mobile = req["mobile"] if "mobile" in req else ""
        email = req["email"] if "email" in req else ""
        login_name = req["login_name"] if "login_name" in req else ""
        login_pwd = req["login_pwd"] if "login_pwd" in req else ""
        id = req["id"] if "id" in req else 0
        resp = {"code": 200, "msg": "操作成功", "data": {}}
        # return jsonify(resp)
        # 验证登录名是否被注册 在添加账号时，User.uid != id才会成立
        has_in = User.query.filter(User.login_name == login_name, User.uid != id).first()
        if has_in:
            resp["code"] = -1
            resp["msg"] = "该登录名已经存在，请换一个试一试 "
            return jsonify(resp)
        # 编辑or添加账号？
        user_info = User.query.filter_by(uid=id).first()
        if user_info:  # 能拿到就是编辑请求
            # 如果admin账号，不允许修改
            if user_info and user_info.uid == 1:
                resp["code"] = -1
                resp["msg"] = "该用户是admin账号，不允许修改编辑 "
                return jsonify(resp)
            model_user = user_info
        else:  # 拿不到就是新增账号请求
            model_user = User()  # 新建一个User实例
            model_user.login_salt = UserService.genSalt(16)  # 自动产生一个加盐数据
            model_user.created_time = datetime.datetime.now()

        # 新增和修改都需要更新数据
        model_user.nickname = nickname
        model_user.mobile = mobile
        model_user.email = email
        model_user.login_name = login_name

        if login_pwd != '******':  # 表示修改了密码 重新生成密码保存，要结合前端的密码默认值比较
            model_user.login_pwd = UserService.gen_pwd(login_pwd, model_user.login_salt)
        # 取修改时间
        model_user.updated_time = datetime.datetime.now()
        # 提交事务到数据库
        db.session.add(model_user)
        db.session.commit()

        return jsonify(resp)


# 删除操作
@route_account.route('/ops', methods=['POST'])
def ops():
    resp = {"code": 200, "msg": "操作成功", "data": {}}
    req = request.values
    act = req["act"] if "act" in req else ""
    id = req["id"] if "id" in req else 0
    print('获取到的数据:', act, id)

    # 非法操作判断逻辑
    if act not in ["remove", "recover"]:
        resp["code"] = -1
        resp["msg"] = "操作有误"
        return jsonify(resp)
    if not id:
        resp["code"] = -1
        resp["msg"] = "请选择要操作的账号"
        return jsonify(resp)

    # 查询数据库uid符合的数据
    user_info = User.query.filter_by(uid=id).first()
    if not user_info:
        resp["code"] = -1
        resp["msg"] = "指定账号不存在"
        return jsonify(resp)
    if user_info and user_info.uid == 1:
        resp["code"] = -1
        resp["msg"] = "该用户是admin账号，不允许修改编辑 "
        return jsonify(resp)

    # 在js里依据状态0和1来决定显示的内容
    if act == "remove":  # 变成删除状态
        user_info.status = 0
    elif act == "recover":  # 变成不删除状态
        user_info.status = 1  # 回复状态
    user_info.updated_time = datetime.datetime.now()
    # 提交数据库
    db.session.add(user_info)
    db.session.commit()
    return jsonify(resp)